package com.good.child.widgets.dialog;

import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;

import com.good.child.R;
import com.good.child.bean.common.AppVersion;
import com.good.child.ui.activity.constants.update.DownloadUtils;
import com.good.child.ui.activity.constants.update.IUpdateDownload;
import com.good.child.ui.utils.CommonU;
import com.yimidida.library.utils.ToastUtil;

import java.text.SimpleDateFormat;
import java.util.Date;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * Create on: 2024/8/4
 * by Mr.Zhu
 * Description: TODO
 */
public class AppUpdateFragment extends DialogFragment implements DownloadUtils.DownloadCallback {
//    @BindView(R.id.tv_app_name)
//    TextView tvAppName;
//    @BindView(R.id.tv_app_version)
//    TextView tvAppVersion;
//    @BindView(R.id.tv_app_size)
//    TextView tvAppSize;
//    @BindView(R.id.tv_update_desc)
//    TextView tvUpdateDesc;
//    @BindView(R.id.tv_cancel)
//    TextView tvCancel;
//    @BindView(R.id.tv_update)
//    ProgressButton tvUpdate;

    @BindView(R.id.update_content_tv)
            TextView contentTv;
    @BindView(R.id.update_cancel_image)
    ImageView cancelImage;
    @BindView(R.id.update_confirm_image)
    ImageView confirmImage;
    Unbinder unbinder;
    private AppVersion appVersion;

    public static void show(FragmentManager fragmentManager, AppVersion appVersion) {
        Fragment fragment = fragmentManager.findFragmentByTag(AppUpdateFragment.class.getCanonicalName());
        if (fragment == null) {
            fragmentManager.beginTransaction()
                    .add(newInstance(appVersion), AppUpdateFragment.class.getCanonicalName())
                    .commitAllowingStateLoss();
        }
    }

    /**
     * @param appVersion 更新数据
     * @return
     */
    public static AppUpdateFragment newInstance(AppVersion appVersion) {
        AppUpdateFragment fragment = new AppUpdateFragment();
        fragment.appVersion = appVersion;
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStyle(DialogFragment.STYLE_NO_TITLE, R.style.BottomDialog);
    }

    @Override
    public void onStart() {
        super.onStart();
        // 设置宽度为屏宽, 靠近屏幕底部。
        Window win = getDialog().getWindow();
        win.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        DisplayMetrics dm = new DisplayMetrics();
        getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
        WindowManager.LayoutParams params = win.getAttributes();
        params.gravity = Gravity.CENTER;
        // 使用ViewGroup.LayoutParams，以便Dialog 宽度充满整个屏幕
//        params.width = ViewGroup.LayoutParams.MATCH_PARENT;
        params.width = (int) (dm.widthPixels / 1.3);
        params.height = (int) (dm.heightPixels / 1.3);
        win.setAttributes(params);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.dialog_app_version_update_new, container, false);
        unbinder = ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        if (appVersion == null) {
            dismissAllowingStateLoss();
            return;
        }
//        tvAppName.setText(appVersion.getAppName());
//        tvAppSize.setText(appVersion.getUpgradePackageSize());
//        tvAppVersion.setText(appVersion.getClientVersion());
//        tvUpdateDesc.setText(appVersion.getUpdateLog());
//        tvUpdateDesc.setMovementMethod(ScrollingMovementMethod.getInstance());
        contentTv.setText(appVersion.getUpdateLog());
        //是否强制安装 1强制2兼容
        cancelImage.setVisibility(appVersion.isForceUpdate() ? View.GONE : View.VISIBLE);
        if (!TextUtils.isEmpty(appVersion.getTolerantVersion()) && !appVersion.isForceUpdate()) {
            try {
                int verCode = Integer.parseInt(appVersion.getTolerantVersion());
                cancelImage.setVisibility(CommonU.getVersionCode(getContext()) >= verCode ? View.VISIBLE : View.GONE);
            } catch (Exception e) {
            }
        }
        if (appVersion.isForceUpdate()) {
            getDialog().setOnKeyListener(new DialogInterface.OnKeyListener() {
                @Override
                public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                    return keyCode == KeyEvent.KEYCODE_BACK;
                }
            });
        }
        getDialog().setCanceledOnTouchOutside(!appVersion.isForceUpdate());
    }

    @Override
    public void onPause() {
        super.onPause();
//        Activity topActivity = ActivityManager.getTopActivity();
//        if (topActivity != null && topActivity.getClass() == OfflineDialogActivity.class) {
//            dismissAllowingStateLoss();
//        }
    }

    /**
     * 返回键处理，如果需要拦截返回键，请调用此方法
     *
     * @return
     */
    public boolean onBackPressed() {
        return cancelImage.getVisibility() != View.VISIBLE;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @Override
    public void onResume() {
        super.onResume();
        if (appVersion != null && appVersion.isForceUpdate() && updateDownload != null) {
            updateDownload.reInstall();
        }
    }

    private IUpdateDownload updateDownload;

    @OnClick({R.id.update_cancel_image, R.id.update_confirm_image})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.update_cancel_image:
                dismiss();
                break;
            case R.id.update_confirm_image:
                String fileName = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date()) + ".apk";
                updateDownload = IUpdateDownload.download(getContext(), appVersion.getDownloadUrl(), fileName, this);
                ToastUtil.showShort(getString(R.string.str_downloading));
                if (appVersion != null && appVersion.isForceUpdate()) {
                    //如果是强制更新，不关闭窗口，必须等待下载完成
//                    tvUpdate.setText(getString(R.string.str_wait_download));
                    view.setEnabled(false);
                    return;
                }
                dismiss();
                break;
        }
    }

    @Override
    public void onDownloading(int present) {
//        if (tvUpdate == null)
//            return;
//        tvUpdate.post(() -> {
//            if (tvUpdate == null)
//                return;
//            tvUpdate.setMaxProgress(100);
//            tvUpdate.setProgress(present);
//        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (updateDownload != null) {
            updateDownload.onDestroy();
        }
    }

    @Override
    public void onDownloadFail() {
//        if (tvUpdate == null)
//            return;
        confirmImage.postDelayed(new Runnable() {
            @Override
            public void run() {
//                if (tvUpdate == null)
//                    return;
                dismissAllowingStateLoss();
                ToastUtil.showShort(getString(R.string.str_update_fail));
            }
        }, 3000);
    }
}

